package org.hako.recite.word.tool.writer;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.hako.recite.word.model.Word;
import org.hako.recite.word.parser.WordList;

/**
 * Write word list to text file.
 * 
 * @since 0.4.9
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class TextFileWordListWriter extends AbstractWordListFileWriter {

	@Override
	public void write(WordList wordList, OutputStream outputStream)
			throws WordListWriteException {
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				outputStream));
		try {
			writeFields(writer, wordList.getColumnTitles());
			writer.newLine();
			for (Word word : wordList) {
				String[] fields = word.getFields();
				writeFields(writer, fields);
				writer.newLine();
			}
			writer.flush();
		} catch (IOException e) {
			throw new WordListWriteException(e);
		}
	}

	/**
	 * Write fields.
	 * 
	 * @param writer
	 * @param fields
	 * @throws IOException
	 */
	private void writeFields(BufferedWriter writer, String[] fields)
			throws IOException {
		writeFields(writer, fields.length, fields);
	}

	/**
	 * Write fields.
	 * 
	 * @param writer
	 * @param columnCount
	 * @param fields
	 * @throws IOException
	 */
	private void writeFields(BufferedWriter writer, int columnCount,
			String[] fields) throws IOException {
		for (int column = 0; column < columnCount; column++) {
			writer.write(fields[column]);
			writer.write('\t');
		}
	}
}
